<template>
  <div class="newpeople">
    <!-- 人员设置 form -->
    <el-row :gutter="24" class="form" id="formt" style="background:#fff; position: relative;">
      <el-col :span="7">
        <div class="grid-content">
          <el-form :model="searchForm" label-width="95px" @submit.native.prevent class="demo-form">
            <el-form-item label="用 户 名" class="img-name">
              <el-input
                v-model="searchForm.loginName"
                placeholder="请选择用户名称"
                style="width: 200px;"
                clearable
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col :span="7">
        <div class="grid-content">
          <el-form :model="searchForm" label-width="95px" @submit.native.prevent class="demo-form">
            <el-form-item label="角色权限" class="img-name">
              <el-select
                v-model="searchForm.roleCode"
                clearable
                placeholder="请选择角色权限"
                style="width: 200px;"
              >
                <el-option
                  :label="item.name"
                  :value="item.id"
                  v-for="(item, index) in roleEnum"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col :span="7">
        <div class="grid-content date-picker">
          <el-form :model="searchForm" label-width="95px" @submit.native.prevent class="demo-form">
            <el-form-item label="注册时间" class="img-name">
              <el-date-picker
                placeholder="请选择注册时间"
                style="margin-left:40px; width: 200px"
                v-model="searchForm.startDate"
                type="date"
              ></el-date-picker>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col :span="3" class="btn-cx">
        <div class="grid-content">
          <el-form
            :model="searchForm"
            label-width="100px"
            @submit.native.prevent
            style="float: right"
          >
            <el-button type="primary" @click="search" class="search-btn">查询</el-button>
          </el-form>
        </div>
      </el-col>
    </el-row>
    <!-- 人员列表 -->
    <div class="poeple-list">
      <div class="add-user">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleInsert"
          v-has-permission="'user_insert'"
        >新增用户</el-button>
      </div>
      <el-table
        :data="listData"
        stripe
        class="reg-tab"
        :header-cell-style="getRowClass"
        v-loading="loading"
      >
        <el-table-column
          :prop="item.prop"
          :label="item.label"
          v-for="(item, index) in tableHead"
          :key="index"
          :formatter="item.prop === 'roleCode' ? roleFormatter : null"
        ></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="handleEdit(scope.row)"
              title="编辑"
              v-has-permission="'user_update'"
            >
              <img src="../../../../../static/image/common/edit.png" alt>
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="handleView(scope.row)"
              title="查看"
              v-has-permission="'user_query'"
            >
              <img src="../../../../../static/image/common/preview.png" alt>
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="handleDelete(scope.row)"
              title="删除"
              v-has-permission="'user_delete'"
            >
              <img src="../../../../../static/image/common/delete.png" alt>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <div class="page-left">
          <span>共{{ this.total}}条数据</span>
          <span>每页:</span>
          <el-input
            placeholder="条数"
            v-model="inputs"
            @blur="pagesizeChange"
            @keyup.enter.native="pagesizeChange"
            clearable
          ></el-input>
          <span>条</span>
        </div>
        <el-pagination
          background
          layout="prev, pager, next, jumper"
          :page-size="pageSize"
          :total="total"
          @current-change="handleCurrentChanges"
          id="page"
          :current-page.sync="currentPage"
        ></el-pagination>
      </div>
    </div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="resetPeopleForm"
      width="420px"
      class="center"
    >
      <view-people :people-form="peopleForm" v-if="isView"></view-people>
      <create-people
        :form="peopleForm"
        @hide="hideDialog"
        v-if="!isView"
        :dialogVisible="dialogVisible"
        :title="title"
        :role-enum="createRoleEnum"
      ></create-people>
    </el-dialog>
    <!--删除弹出框-->
    <delete-dialog :is-show="deleteDialogShow" :desc="deleteDesc" @close="handleClose"></delete-dialog>
  </div>
</template>

<script>
import CreatePeople from "./createPeople";
import ViewPeople from "./ViewPeople";
import DeleteDialog from "../../../../components/CommonDialog";
import Config from "../../../../config";
import { mapGetters } from "vuex";
export default {
  name: "people",
  components: {
    CreatePeople,
    ViewPeople,
    DeleteDialog
  },
  data() {
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号不能为空"));
      } else {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
        if (reg.test(value)) {
          callback();
        } else {
          return callback(new Error("请输入正确的手机号"));
        }
      }
    };
    return {
      tableHead: [
        { prop: "index", label: "序号" },
        { prop: "loginName", label: "用户名" },
        { prop: "name", label: "姓名" },
        { prop: "phone", label: "电话号码" },
        { prop: "roleCode", label: "角色权限" },
        { prop: "districtName", label: "管辖区域" },
        { prop: "createTime", label: "注册时间" }
      ],
      // 表格数据
      listData: [],
      rules: {
        loginName: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          { min: 2, max: 5, message: "长度在 2 到 5 个字符", trigger: "blur" }
        ],
        phone: [{ required: true, validator: checkPhone, trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }]
      },
      // 删除弹出框
      deleteDialogShow: false,
      deleteDesc: '',
      // 删除对象
      deleteObject: null,
      dialogVisible: false,
      // 是否预览
      isView: false,
      title: "",
      PEOPLE_INSERT: "新增用户",
      PEOPLE_EDIT: "用户编辑",
      PEOPLE_VIEW: "用户预览",
      peopleForm: null,
      // 查询
      searchForm: {
        loginName: "",
        roleCode: "",
        startDate: null
      },
      roleEnum: [],
      // 分页
      total: 1,
      currentPage: 1,
      pageSize: 15,
      inputs: 15,
      // loading
      loading: false
    };
  },
  computed: {
    ...mapGetters("user", {
      role: "getRole",
      button: "getButton",
      district: "getDistrict"
    }),
    // 当前用户可以创建的角色
    // TODO 简单进行了sort大小判断，还需要进行类型判断(比如只能创建同一类的角色)
    createRoleEnum() {
      const temArr = [];
      this.roleEnum.forEach(item => {
        if (item.sort < this.role[0].sort) {
          // 对角色进行过滤，只能创建小于当前登录用户级别的角色
          temArr.push(item);
        }
      });

      return temArr;
    }
  },
  mounted() {
    this.resetPeopleForm();
    this.getPeople();
    this.getAllRoleType();
  },
  methods: {
    /**
     * 获取所有的角色列表
     * */
    getAllRoleType() {
      const url = `${Config.AUTH_URL}/role/getAll`;
      this.$http.get(url).then(data => {
        this.roleEnum.splice(0);
        data.forEach(item => {
          this.roleEnum.push(item);
        });
      });
    },
    /**
     * 当前页变化
     * */
    handleCurrentChanges(val) {
      console.log(val)
      this.currentPage = val;
      this.getPeople();
    },
    /**
     * 每页大小变化
     * */
    pagesizeChange() {
      if (+this.inputs === 0) {
        this.inputs = 15;
      }
      if (Number.isInteger(+this.inputs)) {
        this.pageSize = +this.inputs;
        this.getPeople();
      } else {
        this.$message({
          message: "请输入整数",
          type: "warning"
        });
      }
    },
    /**
     * 从后台获取人员列表
     * */
    getPeople() {
      const url = `${Config.AUTH_URL}/getUserInfoByPage`;
      let param = {
        offset: this.currentPage - 1,
        pagesize: this.pageSize
      };
      const date = this.searchForm.startDate;
      if (date) {
        param.startDate = `${this.$util.Date.getYear(
          date
        )}-${this.$util.Date.getMonth(date)}-${this.$util.Date.getDate(date)}`;
      }
      const roleCode = this.searchForm.roleCode;
      if (roleCode) {
        param.roleCode = roleCode;
      }
      const loginName = this.searchForm.loginName;
      if (loginName) {
        param.loginName = loginName;
      }

      param = this.preHandleParam(param);
      this.$http.get(url, param).then(data => {
        const list = data.pageList;
        this.listData.splice(0);
        list.forEach((item, i) => {
          if (this.currentPage === 1) {
            item.index = i + 1;
          } else {
            item.index = (this.currentPage - 1) * this.pageSize + i + 1;
          }
          // item.index = index;
          this.listData.push(item);
        });
        this.total = data.totalCount;
      });
    },
    /**
     * 预处理查询参数
     * @param {JSON} param
     * */
    preHandleParam(param) {
      const provinceCode = this.district.provinceCode || "";
      const cityCode = this.district.cityCode || "";
      const areaCode = this.district.areaCode || "";
      const districtId = this.district.districtId || "";
      if (areaCode) {
        // 包含区编码,角色为场所管理员
        if (districtId) {
          param = { ...param, ...{ districtId } };
        }
      } else {
        if (cityCode) {
          // 包含市编码
          param = { ...param, ...{ cityCode } };
        } else {
          if (provinceCode) {
            // 包含省编码
            param = { ...param, ...{ provinceCode } };
          }
        }
      }
      return param;
    },
    /**
     * 表头添加背景颜色
     * */
    getRowClass({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return "background:#fafbfc";
      } else {
        return "";
      }
    },
    /**
     * 表格格式化roleCode一列
     * */
    roleFormatter(row, column) {
      let text = "";
      this.roleEnum.some(role => {
        if (role.id === row.roleCode) {
          text = role.name;
          return true;
        }
      });
      return text;
    },
    /**
     * 根据条件搜索搜索
     * */
    search() {
      this.currentPage = 1;
      this.pageSize = 15;
      this.getPeople();
    },
    /**
     * 新增用户
     * */
    handleInsert() {
      this.title = this.PEOPLE_INSERT;
      this.resetPeopleForm();
      this.dialogVisible = true;
      this.isView = false;
    },
    /**
     * 重置用户
     * */
    resetPeopleForm() {
      this.peopleForm = null;
      this.peopleForm = {
        loginName: "",
        name: "",
        phone: "",
        roleCode: "",
        area: "",
        createTime: "",
        districtId: "",
        districtName: "",
        districtType: "",
        provinceCode: "",
        cityCode: "",
        areaCode: ""
      };
    },
    /**
     * 编辑用户
     * */
    handleEdit(row) {
      this.title = this.PEOPLE_EDIT;
      this.peopleForm = null;
      this.peopleForm = row;
      this.dialogVisible = true;
      this.isView = false;
    },
    /**
     * 用户预览
     * */
    handleView(row) {
      this.title = this.PEOPLE_VIEW;
      this.peopleForm = null;
      this.peopleForm = row;
      this.dialogVisible = true;
      this.isView = true;
    },
    /**
     * 删除用户
     * */
    handleDelete(row) {
      axios({
        method: "get",
        url: `${Config.AUTH_URL}/userDeleteLog/getDeleteCountByUserId?date=${this.$util.Date.getNowDate()}`,
        headers: {
          token: sessionStorage.getItem('token')
        }
      }).then(res => {
        console.log(res)
          if (res.data.data <= 20) {
            this.deleteObject = row
            this.deleteDialogShow = true
            this.deleteDesc = `确定要删除${row.name}吗？`
        } else{
          this.$message({
            message: "您已删除超过20个人员，已通知主运营公司管理员,如需删除人员,请于明天再进行删除操作。",
            type: "error"
          })
        }
        }).catch( error => {})
    },
    handleClose(id) {
      this.deleteDialogShow = false;
      if (!id) {
        this.deleteObject = null;
        return;
      }
      const url = `${Config.AUTH_URL}/user/delete?id=${this.deleteObject.id}`;
      this.$http.post(url).then(data => {
        this.deleteObject = null;
        this.$message.success("删除成功");
        this.getPeople();
      });
    },
    /**
     * 关掉dialog
     * */
    hideDialog(success) {
      if (success === "cancel") {
        this.dialogVisible = false;
        return;
      }
      if (success === true) {
        this.$message.success("保存成功");
        this.resetPeopleForm()
        console.log('this.peopleForm ', this.peopleForm)
        this.dialogVisible = false;
        this.getPeople();
        return;
      }
      this.$message.success("保存失败");
    }
  }
};
</script>

<!-- Add 'scoped' attribute to limit CSS to this component only -->
<style lang='scss' scoped>
@import "../../../../../static/scss/common";
.newpeople {
  .el-input.is-disabled .el-input__inner {
    color: #606266;
    border: 0;
    background-color: #fff;
  }
  .el-row {
    padding: 0;
    .el-col {
      padding: 0 !important;
    }
  }
  .el-form {
    height: 110px;
    display: flex;
    align-items: center;
  }
  .el-form-item.img-name {
    font-family: "微软雅黑";
    font-size: 12px !important;
    font-weight: bold;
    color: #444;
    position: relative;
  }
  .el-form-item__label {
    font-size: 12px !important;
    padding: 0;
    text-align: left;
    text-indent: 51px;
  }
  .img-name /deep/ .el-form-item__label:before {
    position: absolute;
    display: block;
    left: 24px;
    top: 13px;
    content: " ";
    width: 15px;
    height: 20px;
    background: url("../../../../../static/image/common/left.png") no-repeat;
  }
  .img-name /deep/ .el-form-item__label:after {
    position: absolute;
    display: block;
    left: 104px;
    top: 13px;
    content: " ";
    width: 20px;
    height: 20px;
    background: url("../../../../../static/image/common/right.png") no-repeat;
  }
  .date-picker /deep/ .el-input--prefix .el-input__inner {
    padding-left: 30px;
  }
  .el-form-item.img-name {
    margin: 10px 0 10px 0;
  }
  .form .el-input__inner {
    height: 28px !important;
    line-height: 28px !important;
    border: 1px solid #e4e4e4;
    padding: 0 0 0 10px !important;
    .el-icon-time {
      line-height: 0;
    }
    .el-range-separator {
      line-height: 25px;
    }
  }
  .form.el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .poeple-list {
    width: 100%;
    height: auto;
    background: $white;
    margin-top: 20px;
    .add-user {
      height: 24px;
      line-height: 24px;
      margin-right: 27px;
      text-align: right;
      padding-top: 16px;
    }
    .pagination {
      padding: 32px 0 44px 23px;
      .page-left {
        font-size: 12px;
        display: inline-block;
        .el-input--suffix {
          width: 56px;
        }
      }
    }
  }
}
</style>
